<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    title="配置源应用"
    width="800px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref } from 'vue';
  import { BasicForm, useForm } from '@/components/Form';
  import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
  import { FormSchema } from '@/components/Table';
  import { getSimpleConnectionList } from '@/api/connection';
  import { setPluginSourceApp } from '@/api/plugin';

  const sourceAppOptions = ref([]);

  const formSchema: FormSchema[] = [
    {
      field: 'source_app',
      label: '应用',
      required: true,
      component: 'Select',
      componentProps: {
        options: sourceAppOptions,
      },
      colProps: { span: 8 },
    },
  ];

  const emit = defineEmits(['success', 'register']);

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 90,
    baseColProps: { span: 24 },
    schemas: formSchema,
    showActionButtonGroup: false,
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    resetFields();
    await initSourceAppOptions();
    setFieldsValue({
      source_app: data.sourceApp,
    });
    setDrawerProps({ confirmLoading: false });
  });

  async function initSourceAppOptions() {
    const params ={
      state: 'ongoing',
      type: 'app',
    };
    const response = await getSimpleConnectionList(params);
    sourceAppOptions.value = response.items.map(item => ({
        label: item.partner.name,
        value: item.partner.id
    }));
  }

  async function handleSubmit() {
    try {
      const values = await validate();
      setDrawerProps({ confirmLoading: true });
      await setPluginSourceApp(values);
      closeDrawer();
      emit('success');
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>